<?php

/**
 * Klasa walidująca poprawność hasła
 *
 * @category	Core
 * @package		Core_Validate
 * @copyright	Copyright (c) 2008 Kuśmierz Adam
 */

class Core_Validate_Exists extends Zend_Validate_Abstract
{
	const EXISTS = 'ValueExiststAlready';
	
	/**
	 * @var array
	*/
	protected $_messageTemplates = array(
		self::EXISTS => 'This value has taken'
	);
	
	/**
	 * Callback to Zend_Db_Table method, it should check if selected name exists (or not)
	 *
	 * @var array
	*/
	protected $_callback;
	
	/**
	 * Super parameters to callback
	 *
	 * @var array
	 */
	protected $_callbackParams;
	
	/**
	 * Sets validator options
	 *
	 * @param Zend_Db_Table $modelClass
	 * @param string $method
	 * @param array $params Addiotanal parameters to call $method($value, $params[0], $params[1]...) 
	 * @throws Zend_Validate_Exception
	 * @return void
	 */
	public function __construct(Zend_Db_Table_Abstract $modelClass, $method, $params = array())
	{
		$method = (string) $method;
		
		if (!($modelClass instanceof Zend_Db_Table_Abstract))
			throw new Zend_Validate_Exception('The class ' . get_class($modelClass) . ' isn\'t required instance of Zend_Db_Table');
		
		if (!method_exists($modelClass, $method))
			throw new Zend_Validate_Exception('The method "' . $method . '()" doesn\'t exists in "' . get_class($modelClass) . '" class');
		
		$this->_callback = array($modelClass, $method);
		$this->_callbackParams = (array) $params;
	}
		
	/**
	 * Defined by Zend_Validate_Interface
	 *
	 * Returns true if and only if the password exact match with passwordConfirm value.
	 *
	 * @param  string $value
	 * @return boolean
	 */
	public function isValid($value)
	{
		$value = (string) $value;
		$this->_setValue($value);
		
		if (!call_user_func_array($this->_callback, array_merge(array($value), $this->_callbackParams)))
			return true;
		
		$this->_error(self::EXISTS);
		return false;
	}
}